let maxNo = null;
let lock = true;
$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange, useBeforeClick, useAction }) {
  console.log("Data ready event triggered");
  var mstform = $NG.getCmpApi("p_form_equipment_list");
  var dgrid = $NG.getCmpApi("p_form_equipment_list_d");
  var dgrid1 = $NG.getCmpApi("p_form_equipment_list_impl");
  var dgrid2 = $NG.getCmpApi("p_form_equipment_list_svc");
  var dgrid3 = $NG.getCmpApi("p_form_equipment_list_rd");
  const toolbar_dgrid = $NG.getCmpApi("toolbar_p_form_equipment_list_d");
  let checkImpFlg = true;
  window._lsz_catch_status = {
    impl: [],
    svc: [],
    rd: [],
  };

  ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////
  //按钮点击前事件
  useBeforeClick(async ({ args }) => {
    console.log(`保存`);
    console.log(lock);
    let is = true;
    let isArr = [];
    // checkImpdataStatus();
    // if (checkImpFlg) {
    //   return false;
    // }

    if ($NG.getPageState().data.p_form_equipment_list.phid_schemeid == 8570000000000329) {
      let u_ad_total_amt = mstform.getItem("u_ad_total_amt").getValue();
      let u_total_cost_amt = mstform.getItem("u_total_cost_amt").getValue();
      if (u_total_cost_amt > u_ad_total_amt) {
        $NG.alert(`项目总未税成本 ${u_total_cost_amt} 超过提前施工总投入${u_ad_total_amt}`);
        return false;
      }
      let u_ad_material_amt = mstform.getItem("u_ad_material_amt").getValue();
      let u_pur_cost_amt = mstform.getItem("u_pur_cost_amt").getValue();
      if (u_pur_cost_amt > u_ad_material_amt) {
        $NG.alert(`拟采购成本未税 ${u_pur_cost_amt} 提前施工材料投入${u_ad_material_amt}`);
        return false;
      }
      let u_ad_engineering_amt = mstform.getItem("u_ad_engineering_amt").getValue();
      let u_sub_cost_amt = mstform.getItem("u_sub_cost_amt").getValue();
      if (u_sub_cost_amt > u_ad_engineering_amt) {
        $NG.alert(`拟分包成本未税 ${u_sub_cost_amt} 提前施工工程投入${u_ad_engineering_amt}`);
        return false;
      }
      let u_self_owned_cost = mstform.getItem("u_self_owned_cost").getValue();
      let u_self_cost = mstform.getItem("u_self_cost").getValue();
      if (u_self_cost > u_self_owned_cost) {
        $NG.alert(`拟自制成本未税 ${u_self_cost} 提前施工自主产品投入${u_self_owned_cost}`);
        return false;
      }
      let u_implement_cost = mstform.getItem("u_implement_cost").getValue();
      let u_implement_amt = mstform.getItem("u_implement_amt").getValue();
      if (u_implement_amt > u_implement_cost) {
        $NG.alert(`实施费 ${u_implement_amt} 提前施工实施费用投入${u_implement_cost}`);
        return false;
      }
    }

    await dgrid.getRows().forEach((item, index) => {
      if (item.u_pur_qty) {
        item.u_rest_qty = item.u_pur_qty; // 将u_pur_qty的值赋给u_rest_qty
        console.log(item.u_pur_qty, item.u_rest_qty);
      } else {
        item.u_rest_qty = 0; // 将u_pur_qty的值赋给u_rest_qty
      }
      if (item.u_pur_name) {
        if (!item.u_pur_item_category) {
          is = false;
          isArr.push(index + 1);
        }
      }
    });
    // 查看是否存在清单
    let exit = true;
    console.log(`保存设置1`, lock);
    if (!is) {
      $NG.alert(`设备清单明细第 ${isArr.join("、")} 行 拟采购类型为空`);
      console.log(`错误！！！！！`);
      return false;
    }
    if (!lock) {
      exit = await $NG.confirm("确认提交？");
      console.log(exit, "保存测试");
    }
    console.log(`保存设置2`, exit);

    return exit;
  }, "save");
  useClick(function ({ args }) {
    console.log(args, "1XXX1???");
    useDataFun("ArrData", "clear");
    useDataFun("ArrData", "save", dgrid.getRows());
  }, "imp_push");
  if (toolbar_dgrid) {
    toolbar_dgrid.insert({
      id: "user_insert",
      text: "插行",
      iconCls: "icon-InsertRow",
    });
    toolbar_dgrid.insert({
      id: "template_download",
      text: "模板下载",
      iconCls: "icon-InsertRow",
    });
    // toolbar_dgrid.insert({
    //   id: "imp_updown",
    //   text: "选中后点击穿透到定价申请",
    //   iconCls: "icon-InsertRow",
    // });
    //按钮点击事件
    useClick(async function ({ args }) {
      var data = {
        LinkRep_tarSheets: "0",
        LinkRep_tarCells: "b1",
        LinkRep_srcParas: `${mstform.getItem("u_cnt").getValue()}`,
      };
      var replinkdata = encodeURIComponent(JSON.stringify(data));
      const url = window.location.href;
      const arr = $NG.split(url, "/");
      const url_domain = arr[2];
      const url_path = `/RW/DesignFrame/ReportView?rep_src=0&rep_code=202502100002&replink=true&datavaluetype=cell&replinkdata=${replinkdata}`;
      $NG.open(`http://${url_domain}${url_path}`, { AppTitle: "模板下载" });
    }, "template_download");
    useClick(async function ({ args }) {
      // 构造参数
      const projectSelectionValue = mstform.getItem("phid_pc").getValue(); // 这里是你需要传递的项目选择值，可以是动态获取的值
      // 构造 URL 参数
      const url_domain = "nginx.clouddev.hisense.com"; // 域名
      const url_path = "/report/index.html#/tableDesign/TableManager/preview"; // 路径
      const query_params = `?preview=1&rep_id=8570000000000006&name=%E8%AE%BE%E5%A4%87%E6%B8%85%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF&defaultSheet=0&&linkParams=[{%22paramKey%22:%22%E9%A1%B9%E7%9B%AE%E9%80%89%E6%8B%A9%22,%22dataSetId%22:%228570000000000008%22,%22dataSetSource%22:null,%22paramType%22:%22fixed_value%22,%22paramValue%22:%22${projectSelectionValue}%22,%22valueDataSetId%22:null,%22valueDataSetSource%22:null}]&AppTitle=%E8%AE%BE%E5%A4%87%E6%B8%85%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF&menucode=2c2123a1-8780-4a18-837e-5dd8b9a11ffa`;

      // 打开报表并传递参数
      $NG.open(`http://${url_domain}${url_path}${query_params}`, { AppTitle: "模板下载" });
    }, "template_download2");
    useClick(async function ({ args }) {
      insertClick();
    }, "user_insert");
    // 选中后点击穿透到定价申请
    // 穿透到报表，目前还未做
    useAction("onClick")(() => {
      // $NG.open(`http://nginx.clouddev.hisense.com/react/index.html#/customform/detail?id=${dgrid1.getSelectedData()[0].u_source_phid}&otype=view&busType=EFORM9000000034&isSso=0`, { AppTitle: "实施费用预算" });
    }, "imp_updown");
  }
  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
  if (mstform) {
    //初始化逻辑BEGIN
    mstformUpdateUI();
    cntMFilter();
    cntDFilter();
    if (mstform.getItem("phid_pc").getValue()) {
      getPtInfoByPhid();
      getCntCount("p_form_equipment_list", "u_cnt", getCntMInfoByPhid, danjvchaxun);
    }

    // if (page.oType == "add" || page.oType == "edit" || page.oType == "copy") {
    //   $NG.updateState(function (updater, state) {
    //     if (!mstform.getItem("u_create_org").getValue()) {
    //       updater.data.p_form_equipment_list.setProps({
    //         u_create_org: $NG.getUser().orgID,
    //         u_create_org_EXName: $NG.getUser().orgName,
    //         u_using_org: $NG.getUser().userID,
    //         u_using_org_EXName: $NG.getUser().orgName,
    //       });
    //     }
    //   });
    // }
    useValuesChange(({ args }) => {
      console.log(`实施是否清算监听`, args);
      const _lock = args[0].u_is_implementation_settle.value;
      console.log(`1`);
      $NG.updateUI(function (updater, state) {
        console.log(`实施清算副监听`, updater);
        if (Number(_lock) === 1) {
          console.log(`1`);
          updater.fieldSetForm.p_form_equipment_list.u_implementation_settle_time.setProps({
            required: true, //required是否必输
            disabled: false,
          });
        } else {
          console.log(`0`);
          updater.fieldSetForm.p_form_equipment_list.u_implementation_settle_time.setProps({
            required: false, //required是否必输
            disabled: true,
          });
        }
      });
    }, "p_form_equipment_list.u_is_implementation_settle");
    //服务是否清算监听
    useValuesChange(({ args }) => {
      const _lock = args[0].u_is_service_settle.value;
      $NG.updateUI(function (updater, state) {
        if (Number(_lock) === 1) {
          updater.fieldSetForm.p_form_equipment_list.u_service_settle_time.setProps({
            required: true, //required是否必输
            disabled: false,
          });
        } else {
          updater.fieldSetForm.p_form_equipment_list.u_service_settle_time.setProps({
            required: false, //required是否必输
            disabled: true,
          });
        }
      });
    }, "p_form_equipment_list.u_is_service_settle");
    //项目字段监听
    useValuesChange(({ args }) => {
      cntMFilter();
      getPtInfoByPhid();
      getCntCount("p_form_equipment_list", "u_cnt", getCntMInfoByPhid, danjvchaxun);
    }, "p_form_equipment_list.phid_pc");
    // 合同字段监听
    useValuesChange(({ args }) => {
      cntDFilter();
      getCntMInfoByPhid();
    }, "p_form_equipment_list.u_cnt");
    // 中标服务费监听
    useValuesChange(({ args }) => {
      caculatedgrid();
    }, "p_form_equipment_list.u_win_bid_svc_amt");
    //中标商机字段监听
    useValuesChange(({ args }) => {
      getAdConstructionOpp();
    }, "p_form_equipment_list.u_opportunity_obj");

    $NG.updateUI((updater, state) => {
      updater.fieldSetForm.p_form_equipment_list.u_cnt_no.setProps({
        onDoubleClick() {
          var u_cnt_phid = $NG.getCmpApi("p_form_equipment_list").getItem("u_cnt_no").getValue();
          if (u_cnt_phid) {
            // 弹出确认框
            // var isConfirmed = $NG.confirm("您确定要跳转到合同信息吗？");
            // if (isConfirmed) {
            $NG.open("http://nginx.clouddev.hisense.com" + "/PMS/PCM/CntM/CntMEdit?otype=view&id=" + u_cnt_phid, { AppTitle: "合同信息" });
            // }
          }
        },
      });
    });
  }

  ////////////////////////////////////////////////////////////--dgrid--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--dgrid--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--dgrid--////////////////////////////////////////////////////////////
  if (dgrid) {
    dgridUpdateUI();
    dgridFilter();
    useDataIndexChange(({ args, instance }) => {
      const record = args[0];
      if (record.u_cnt_item) {
        getCntDInfoByPhid(record);
      }
    }, "u_cnt_item");
    useUpdateRow(({ args, table }) => {
      console.log("useUpdateRow begin");
      const items = args[0];
      console.log("测试", items);

      //2. 更新拟分包项
      if (items.u_sub_item) {
        $NG.execServer("getItemdataByPhid", { phid: items.u_sub_item }, function (res) {
          if (res.count > 0) {
            var data = JSON.parse(res.data)[0].extendObjects; //单返回值

            items.u_sub_item_category = data.phid_resbs;
            items.u_sub_item_category_EXName = data.name;
            items.u_sub_name = data.itemname;
            items.u_sub_ggxh = data.spec;
            items.u_sub_item_msunit_EXName = data.msunit_name;
            items.u_sub_item_msunit = data.msunit_phid;
            items.u_sub_item_category = data.phid_resbs;
            items.u_sub_item_category_EXName = data.res_bs_name;
            items.u_fwgczdj = data.prc_ad;
          } else {
            // console.log('没有找到拟分包清单')
            // items.u_u_sub_item = null;
            // items.u_u_sub_item_EXName = null;
            // items.u_sub_ggxh = null;
          }
          dgrid.refreshView();
        });
      }

      //3. 更新拟采购项
      console.log(`编码`, items.u_pur_item);
      if (items.u_pur_item) {
        $NG.execServer("getItemdataByPhid", { phid: items.u_pur_item }, function (res) {
          console.log(`测试请求数据`, res);
          if (res.count > 0) {
            var purdata = JSON.parse(res.data)[0].extendObjects; //单返回值

            items.u_pur_item_category = purdata.phid_resbs;
            items.u_pur_item_category_EXName = purdata.name;
            items.u_pur_name = purdata.itemname;
            items.u_pur_ggxh = purdata.spec;
            items.u_pur_item_msunit_EXName = purdata.msunit_name;
            items.u_pur_item_msunit = purdata.msunit_phid;
            items.u_pur_item_category = purdata.phid_resbs;
            items.u_pur_item_category_EXName = purdata.res_bs_name;
            items.u_cgzdj = purdata.prc_ad;
          } else {
          }
          dgrid.refreshView();
        });
        $NG.execServer(
          "getIsDj",
          {
            phid_wl: items.u_pur_item,
            phid_pc: mstform.getItem("phid_pc").getValue(),
          },
          (res) => {
            console.log(`By物料获得单价信息`, res, mstform.getItem("phid_pc").getValue(), items.u_pur_item);
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            items.u_priced_prc = _data.u_target_prc;
            items.u_is_priced = 1;
            dgrid.refreshView();
          }
        );
      }

      //4. 更新拟自制项
      if (items.u_self_item) {
        $NG.execServer("getItemdataByPhid", { phid: items.u_self_item }, function (res) {
          if (res.count > 0) {
            var data = JSON.parse(res.data)[0].extendObjects; //单返回值

            items.u_self_item_category = data.phid_resbs;
            items.u_self_item_category_EXName = data.name;
            items.u_self_name = data.itemname;
            items.u_self_ggxh = data.spec;
            items.u_self_item_msunit = data.msunit_phid;
            items.u_self_item_msunit_EXName = data.msunit_name;
            items.u_self_item_category_EXName = data.res_bs_name;
            items.u_self_item_category = data.phid_resbs;
            items.u_zzzdj = data.prc_ad;
          } else {
            // console.log('没有找到拟采购清单')
            // items.u_u_pur_item = null;
            // items.u_u_pur_item_EXName = null;
          }
          dgrid.refreshView();
        });
      }

      console.log("useUpdateRow end");
    }, "p_form_equipment_list_d");
    useUpdateRows(({ args, table }) => {
      const rows = args[0];
      const clearList = {}; // 用于存储清单编号
      let clearCodeCounter = 1; // 清单编码计数器，从 1 开始
      let lock = false; //要刷新吗
      caculatedgrid();
      rows.forEach((items, index) => {
        items.u_state = "normal";
        // items.u_state_EXName = "正常";
        if (items.u_self_qty) {
          items.u_nzz_rest_qty = items.u_self_qty;
        } else {
          items.u_nzz_rest_qty = 0;
        }

        //1、自动生成设备清单
        const { u_equipment_list_name, u_model } = items;
        const key = `${u_equipment_list_name}_${u_model}`; // 根据名称和型号生成唯一标识符

        if (!clearList[key]) {
          // 如果清单编号不存在，则生成新的编号
          const serialPart = String(clearCodeCounter).padStart(4, "0"); // 将计数器格式化为4位
          clearList[key] = "A" + serialPart; // 生成清单编号
          clearCodeCounter++;
        }
        //根据导入的合同编码匹配合同清单
        if (!items.u_cnt_item) {
          getCntDInfoByNo(items);
          lock = true;
        }
        console.log(`正则`, /^\d{14}$/.test(items.u_equipment_list_no));
        if (!/^\d{14}$/.test(items.u_equipment_list_no)) {
          items.u_equipment_list_no = autoCreateNo(index + 1);
        }
        if (!items.u_equipment_list_name) {
          items.u_equipment_list_name = items.u_cnt_item_EXName;
        }
        //3、匹配拟分包项
        if (!items.u_sub_item && items.u_sub_no) {
          console.log("通过 u_sub_no 匹配拟分包项");
          $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_sub_no + "'" }, function (res) {
            if (res.count > 0) {
              var data = JSON.parse(res.data)[0].extendObjects; //单返回值
              items.u_sub_item = data.phid;
              items.u_sub_item_EXName = data.itemno;
              items.u_sub_name = data.itemname;
              items.u_sub_item_category = data.phid_resbs;
              items.u_sub_item_category_EXName = data.name;
              items.u_sub_item_msunit_EXName = data.msunit_name;
              items.u_sub_item_msunit = data.msunit_phid;
              items.u_sub_ggxh = data.spec;
              items.u_fwgczdj = data.prc_ad;
            } else {
              console.log(items.u_sub_no + ":useUpdateRows没有找到拟分包清单");
              // items.u_sub_item = null;
              // items.u_sub_item_EXName = null;
            }
          });
          items.u_sub_invoice_type = "8570000000000151";
          items.u_sub_invoice_type_EXName = "6%增值税专用发票";
          dgrid.refreshView();
        }

        //3、匹配拟采购项目
        if (!items.u_pur_item && items.u_pur_no) {
          console.log("通过 u_pur_no 匹配拟采购项目");
          $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_pur_no + "'" }, function (res) {
            if (res.count > 0) {
              var purdata = JSON.parse(res.data)[0].extendObjects; //单返回值
              items.u_pur_item = purdata.phid;
              items.u_pur_item_EXName = purdata.itemno;
              items.u_pur_name = purdata.itemname;
              items.u_pur_item_category = purdata.phid_resbs;
              items.u_pur_item_category_EXName = purdata.name;
              items.u_pur_item_msunit = purdata.msunit_phid;
              items.u_pur_item_msunit_EXName = purdata.msunit_name;
              items.u_pur_ggxh = purdata.spec;
              items.u_cgzdj = purdata.prc_ad;
            } else {
              console.log("useUpdateRows没有找到拟采购清单");
              // items.u_u_pur_item = null;
              // items.u_u_pur_item_EXName = null;
            }
          });
          $NG.execServer(
            "getIsDj",
            {
              phid_wl: items.u_pur_item,
              phid_pc: mstform.getItem("phid_pc").getValue(),
            },
            (res) => {
              console.log(`By物料获得单价信息`, res, mstform.getItem("phid_pc").getValue(), items.u_pur_item);
              if (res.count == 0) return;
              const _data = JSON.parse(res.data)[0].extendObjects;
              items.u_priced_prc = _data.u_target_prc;
              items.u_is_priced = 1;
              dgrid.refreshView();
            }
          );
          items.u_pur_invoice_type = "8570000000000154";
          items.u_pur_invoice_type_EXName = "13%增值税专用发票";
          dgrid.refreshView();
        }

        //4、匹配自制项目
        if (!items.u_self_item && items.u_self_no) {
          console.log("通过 u_self_no 匹配自制项目");
          $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_self_no + "'" }, function (res) {
            if (res.count > 0) {
              var data = JSON.parse(res.data)[0].extendObjects; //单返回值

              items.u_self_item = data.phid;
              items.u_self_item_EXName = data.itemno;
              items.u_self_name = data.itemname;
              items.u_self_item_category = data.phid_resbs;
              items.u_self_item_category_EXName = data.name;
              items.u_self_ggxh = data.spec;
              items.u_self_item_msunit = data.msunit_phid;
              items.u_self_item_msunit_EXName = data.msunit_name;
              items.u_zzzdj = data.prc_ad;
            } else {
              console.log("useUpdateRows没有找到拟自制清单");
              // items.u_self_item = null;
              // items.u_self_item_EXName = null;
            }
            dgrid.refreshView();
          });
        }
        dgrid.refreshView();
      });
      rows.forEach((items, index) => {
        // // 未税单价   = 含税单价/1+税率
        // args[0].u_sub_prc = (args[0].u_sub_prc_vat || 0) / (1 + (args[0].u_sub_tax_rate || 0));
        // 含税单价   = 未税单价*（1+税率）
        items.u_sub_prc_vat = (items.u_sub_prc || 0) * (1 + (items.u_sub_tax_rate || 0));
        // 含税成本 = 数量 * 含税单价
        items.u_sub_cost_vat = (items.u_sub_qty || 0) * (items.u_sub_prc_vat || 0);
        // 成本未税 = 数量 * 含税单价 / 1+税率
        items.u_sub_cost = (items.u_sub_qty || 0) * (items.u_sub_prc || 0);
        // items.u_sub_cost = ((items.u_qty || 0) * (items.u_sub_prc_vat || 0)) / (1 + (items.u_sub_tax_rate || 0));

        // 采购
        // items.u_pur_prc = (items.u_pur_prc_vat || 0) / (1 + items.u_pur_tax_rate || 0);
        items.u_pur_prc_vat = (items.u_pur_prc || 0) * (1 + items.u_pur_tax_rate || 0);
        items.u_pur_cost_vat = (items.u_pur_qty || 0) * (items.u_pur_prc_vat || 0);
        items.u_pur_cost = (items.u_pur_qty || 0) * (items.u_pur_prc || 0);
        // items.u_pur_cost = ((items.u_qty || 0) * (items.u_pur_prc_vat || 0)) / (1 + (items.u_pur_tax_rate || 0));

        // 自制
        // items.u_self_prc = (items.u_self_prc_vat || 0) * (1 + items.u_self_tax_rate || 0);
        items.u_self_prc_vat = (items.u_self_prc || 0) * (1 + items.u_self_tax_rate || 0);
        items.u_self_cost_vat = (items.u_self_qty || 0) * (items.u_self_prc_vat || 0);
        items.u_self_cost = (items.u_self_qty || 0) * (items.u_self_prc || 0);
        // items.u_self_cost = ((items.u_qty || 0) * (items.u_self_prc_vat || 0)) / (1 + (items.u_self_tax_rate || 0));
      });
      if (lock) {
        dgrid.refreshView();
        console.log(`刷新了`);
      }

      console.log("useUpdateRows end");
    }, "p_form_equipment_list_d");
  }

  function useDataFun(k, t, v) {
    function saveData(k, v) {
      localStorage.setItem(k, JSON.stringify(v));
    }
    function getData(k) {
      const storedValue = localStorage.getItem(k);
      if (storedValue) {
        return JSON.parse(storedValue);
      }
      return null;
    }
    function clearData(k) {
      localStorage.removeItem(k);
    }
    function AsyncTypeData(k, t, v) {
      switch (t) {
        case "save":
          saveData(k, v);
          break;
        case "get":
          return getData(k);
          break;
        case "clear":
          clearData(k);
          break;
        default:
          console.log("Invalid t");
      }
    }
    AsyncTypeData(k, t, v);
  }

  // try {
  //   let _num = 0;
  //   setInterval(() => {
  //     const t = dgrid.getRows().length;
  //     if (t !== _num) {
  //       dgrid.refreshView();
  //       _num = t;
  //     }
  //   }, 1000);
  // } catch (err) {}

  ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////
  if (dgrid1) {
    var dgrid1_toolbar = $NG.getCmpApi("toolbar_p_form_equipment_list_impl");
    dgrid1_toolbar.hideButton("addrow");
    dgrid1_toolbar.hideButton("deleterow");
    dgrid1_toolbar.hideButton("imp");
    dgrid1_toolbar.hideButton("import");
    dgrid1_toolbar.hideButton("attachment");
    dgrid1_toolbar.insert({
      id: "dgrid1Click",
      text: "选中后点击穿透到预算单",
      iconCls: "icon-New",
    });
    useAction("onClick")(() => {
      $NG.open(`http://nginx.clouddev.hisense.com/react/index.html#/customform/detail?id=${dgrid1.getSelectedData()[0].u_source_phid}&otype=view&busType=EFORM9000000034&isSso=0`, { AppTitle: "实施费用预算" });
    }, "dgrid1Click");

    useUpdateRows(({ args }) => {
      const rows = args[0];
      caculatedgrid();
    }, "p_form_equipment_list_impl");
    $NG.updateUI((updater) => {
      const fields = ["u_source_phid", "u_data_status"];
      fields.forEach((field) => {
        updater.editGrid.p_form_equipment_list_impl[field].setProps({
          hidden: true, //隐藏
        });
      });
    });
  }

  ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////
  if (dgrid2) {
    var dgrid2_toolbar = $NG.getCmpApi("toolbar_p_form_equipment_list_svc");
    dgrid2_toolbar.hideButton("addrow");
    dgrid2_toolbar.hideButton("deleterow");
    dgrid2_toolbar.hideButton("imp");
    dgrid2_toolbar.hideButton("import");
    dgrid2_toolbar.hideButton("attachment");
    dgrid2_toolbar.insert({
      id: "dgrid2Click",
      text: "选中后点击穿透到预算单",
      iconCls: "icon-New",
    });
    useAction("onClick")(() => {
      $NG.open(`http://nginx.clouddev.hisense.com/react/index.html#/customform/detail?id=${dgrid2.getSelectedData()[0].u_source_phid}&otype=view&busType=EFORM9000000035&isSso=0`, { AppTitle: "服务费用预算" });
    }, "dgrid2Click");
    useUpdateRows(({ args }) => {
      const rows = args[0];
      caculatedgrid();
    }, "p_form_equipment_list_svc");
    $NG.updateUI((updater) => {
      const fields = ["u_source_phid", "u_data_status"];
      fields.forEach((field) => {
        updater.editGrid.p_form_equipment_list_svc[field].setProps({
          hidden: true, //隐藏
        });
      });
    });
  }
  ////////////////////////////////////////////////////////////--dgrid3--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--dgrid3--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--dgrid3--////////////////////////////////////////////////////////////
  if (dgrid3) {
    var dgrid3_toolbar = $NG.getCmpApi("toolbar_p_form_equipment_list_rd");
    dgrid3_toolbar.hideButton("addrow");
    dgrid3_toolbar.hideButton("deleterow");
    dgrid3_toolbar.hideButton("imp");
    dgrid3_toolbar.hideButton("import");
    dgrid3_toolbar.hideButton("attachment");
    dgrid3_toolbar.insert({
      id: "dgrid3Click",
      text: "选中后点击穿透到预算单",
      iconCls: "icon-New",
    });
    useAction("onClick")(() => {
      $NG.open(`http://nginx.clouddev.hisense.com/react/index.html#/customform/detail?id=${dgrid3.getSelectedData()[0].u_source_phid}&otype=view&busType=EFORM9000000129&isSso=0`, { AppTitle: "二开费用预算" });
    }, "dgrid3Click");
    useUpdateRows(({ args }) => {
      const rows = args[0];
      caculatedgrid();
    }, "p_form_equipment_list_rd");
    $NG.updateUI((updater) => {
      const fields = ["u_source_phid", "u_data_status"];
      fields.forEach((field) => {
        updater.editGrid.p_form_equipment_list_rd[field].setProps({
          hidden: true, //隐藏
        });
      });
    });
  }

  //////////////////////////////////////////////////--mstform function--//////////////////////////////////////////////////
  //////////////////////////////////////////////////--mstform function--//////////////////////////////////////////////////
  //////////////////////////////////////////////////--mstform function--//////////////////////////////////////////////////
  // 获取提前施工申请的信息
  function getAdConstructionOpp(params) {
    $NG.execServer("getAdConstructionOpp", { phid: mstform.getItem("u_opportunity_obj").getValue() }, function (res) {
      console.log("getAdConstructionOpp");
      if (res.count > 0) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(datas);
        $NG.updateState((updater) => {
          updater.data.p_form_equipment_list.setProps({
            u_opportunity_obj_no: datas.u_opp_no,
            u_bid_winning_date: datas.u_bid_dt,
            u_cnt_u_opp_amt: datas.u_opp_amt,
            u_winning_bid_amt: datas.u_bid_amt,
            u_ad_total_amt: datas.u_ad_total_amt,
            u_ad_material_amt: datas.u_ad_material_amt,
            u_ad_engineering_amt: datas.u_ad_engineering_amt,
            u_self_owned_cost: datas.u_self_owned_cost,
            u_implement_cost: datas.u_implement_cost,
          });
        });
      } else {
        console.log("功能扩展暂无数据");
      }
    });
  }
  // 获取项目信息
  function getPtInfoByPhid() {
    console.log("getPtInfoByPhid");
    if (mstform.getItem("phid_pc").getValue()) {
      getSbqdCountByPhidPc();
      $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(datas);
        // mstform.getItem("u_regional_center").setValue({
        //   value: datas.regional_center_phid,
        //   label: datas.regional_center_name,
        // });
        $NG.updateState((updater) => {
          //【注意这里的表名不能为控件ID，必须要是表名】
          updater.data.p_form_equipment_list.setProps({
            u_pc_no: datas.pc_no,
            //售前顾问
            u_sqgw: { value: datas.user_sqgw_phid, label: datas.user_sqgw_name },
            //项目经理
            u_project_manager: {
              value: datas.project_manager_phid,
              label: datas.project_manager_name,
            },
            //事业部
            u_division: {
              value: datas.division_phid,
              label: datas.division_name,
            },
            //区域中心
            u_regional_center: {
              value: datas.regional_center_phid,
              label: datas.regional_center_name,
            },
            //项目类型
            u_pc_type: { value: datas.type_phid, label: datas.type_name },
          });
        });
      });
    }
  }
  // 获取合同信息
  function getCntMInfoByPhid(params) {
    $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log("getCntMInfoByPhid");
      console.log(datas);
      //帮助字段赋值
      $NG.updateState((updater) => {
        //【注意这里的表名不能为控件ID，必须要是表名】
        updater.data.p_form_equipment_list.setProps({
          u_total_cnt_amt_vat: datas.cnt_sum_vat_fc,
          u_cnt_amt_vat: datas.cnt_sum_vat_fc,
          u_cnt_no: { value: datas.pcm_phid, label: datas.pcm_no },
          u_product_line: { value: datas.midwife_phid, label: datas.midwife_name },
          u_cnt_type: { value: datas.pct_id, label: datas.pct_name },
          u_customer: { value: datas.customer_id, label: datas.customer_name },
          u_invoice_type: { value: datas.invoice_type_phid, label: datas.invoice_type_name },
          u_cnt_amt: datas.cnt_sum_vat_fc,
        });
      });
    });
  }
  // 合同过滤
  function cntMFilter() {
    $NG.updateUI((updater, state) => {
      updater.fieldSetForm.p_form_equipment_list.u_cnt.setProps({
        onBeforeOpen: async () => {
          var phid_pc = $NG.getCmpApi("p_form_equipment_list").getItem("phid_pc").getValue();
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!$NG.getCmpApi("p_form_equipment_list").getItem("phid_pc").getValue() && {
          clientSqlFilter: {
            bill_type: 1,
            phid_pc: $NG.getCmpApi("p_form_equipment_list").getItem("phid_pc").getValue(),
          },
        }),
      });
    });
  }
  //获取合同数量
  function getCntCount(table, key, fun, otherFun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
      console.log(res, "count");
      switch (res.count) {
        case 0:
          return;
        case 1:
          const datas = JSON.parse(res.data)[0].extendObjects;
          const temp_map = {};
          temp_map[key] = datas.phid;
          temp_map[`${key}_EXName`] = datas.bill_name;
          $NG.updateState((updater) => {
            updater.data[table].setProps({
              ...temp_map,
            });
            setTimeout(() => {
              fun();
              if (otherFun) {
                otherFun();
              }
            }, 200);
          });
      }
    });
  }
  //设备清单数量
  function getSbqdCountByPhidPc() {
    $NG.execServer("getSbqdCountByPhidPc", { phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
      if (res.count == 0) return;
      const _data = JSON.parse(res.data)[0].extendObjects;
      console.log(`清单数量`, _data);
      if (_data.count > 0) {
        lock = false;
      } else {
        lock = true;
      }
    });
  }

  function mstformUpdateUI(params) {
    // 字段隐藏
    const _arrHideM = [
      "u_total_cost_amt_vat",
      "u_total_cost_change",
      "u_pur_cost_vat",
      "u_sub_cost",
      "u_self_cost_vat",
      // "u_pur_reduction_cost",
    ];
    _arrHideM.forEach((field) => {
      $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_equipment_list[field].setProps({
          hidden: true, //隐藏
        });
      });
    });
    if ($NG.getPageState().data.p_form_equipment_list.phid_schemeid == 8570000000000329) {
      $NG.updateUI((updater) => {
        const fields = ["u_cnt", "u_cnt_no", "u_invoice_type", "u_cnt_type", "u_cnt_amt"];
        fields.forEach((field) => {
          updater.fieldSetForm.p_form_equipment_list[field].setProps({
            required: false, //必输
            disabled: true, //只读
            hidden: true, //隐藏
          });
        });
      });
    } else {
      $NG.updateUI((updater) => {
        const fields = ["u_ad_total_amt", "u_ad_material_amt", "u_ad_engineering_amt", "u_self_owned_cost", "u_implement_cost", "u_opportunity_obj_no", "u_opportunity_obj", "u_bid_winning_date", "u_opp_amt", "u_winning_bid_amt"];
        fields.forEach((field) => {
          updater.fieldSetForm.p_form_equipment_list[field].setProps({
            hidden: true, //隐藏
            required: false, //必输
            disabled: true, //只读
          });
        });
      });
    }
  }
  //////////////////////////////////////////////////--dgrid function--//////////////////////////////////////////////////
  //////////////////////////////////////////////////--dgrid function--//////////////////////////////////////////////////
  //////////////////////////////////////////////////--dgrid function--//////////////////////////////////////////////////

  function dgridUpdateUI(params) {
    //按钮隐藏
    $NG.getCmpApi("toolbar_p_form_equipment_list_d").getItem("attachment").setHidden();
    const _arrHideD = ["u_cnt_prc_vat", "u_cnt_amt_vat", "u_sub_no", "u_sub_prc_vat", "u_sub_cost_vat", "u_sub_invoice_type", "u_pur_no", "u_pur_prc_vat", "u_pur_cost_vat", "u_pur_invoice_type", "u_self_no", "u_self_prc_vat", "u_self_cost_vat", "u_self_invoice_type"];
    _arrHideD.forEach((item) => {
      if (item.includes("sub")) {
        $NG.updateUI((updater) => {
          updater.editGrid.p_form_equipment_list_d["Cell60"][item].setProps({
            hidden: true, //隐藏
          });
        });
      } else if (item.includes("pur")) {
        $NG.updateUI((updater) => {
          updater.editGrid.p_form_equipment_list_d["Cell61"][item].setProps({
            hidden: true, //隐藏
          });
        });
      } else if (item.includes("self")) {
        $NG.updateUI((updater) => {
          updater.editGrid.p_form_equipment_list_d["Cell62"][item].setProps({
            hidden: true, //隐藏
          });
        });
      }
    });
  }
  function dgridFilter(params) {
    // 拟分包项分类过滤;
    $NG.updateUI((updater) => {
      updater.editGrid.p_form_equipment_list_d["Cell60"].u_sub_item_category.setProps({
        clientSqlFilter: `res_bs.resource_type='8570000000000002'`,
      });
    });
    $NG.updateUI((updater) => {
      updater.editGrid.p_form_equipment_list_d["Cell60"].u_sub_item.setProps({
        clientSqlFilter: `res_bs.resource_type='8570000000000002'`,
      });
    });

    // 拟采购项分类过滤;
    $NG.updateUI((updater) => {
      updater.editGrid.p_form_equipment_list_d["Cell61"].u_pur_item_category.setProps({
        clientSqlFilter: `res_bs.resource_type='2'`,
      });
    });
    $NG.updateUI((updater) => {
      updater.editGrid.p_form_equipment_list_d["Cell61"].u_pur_item.setProps({
        clientSqlFilter: `res_bs.resource_type='2'`,
      });
    });
    // 拟自制项分类过滤;
    $NG.updateUI((updater) => {
      updater.editGrid.p_form_equipment_list_d["Cell62"].u_self_item_category.setProps({
        clientSqlFilter: `res_bs.resource_type='8570000000000001'`,
      });
    });
    $NG.updateUI((updater) => {
      updater.editGrid.p_form_equipment_list_d["Cell62"].u_self_item.setProps({
        clientSqlFilter: `res_bs.resource_type='8570000000000001'`,
      });
    });
  }

  function caculatedgrid() {
    console.log("caculatedgrid begin");
    let sum_cost_vat = 0;
    let sum_cost = 0;
    let sum_cnt_amt_vat = 0;
    let sum_sub_cost_vat = 0;
    let sum_sub_cost = 0;
    let sum_pur_cost_vat = 0;
    let sum_pur_cost = 0;
    let sum_self_cost_vat = 0;
    let sum_self_cost = 0;
    let sum_impl_cost_vat = 0; //实施费
    let sum_svc_cost_vat = 0; //服务成本
    let sum_sec_dev_amt = 0; //二次开发费
    let u_total_cnt_amt_vat = mstform.getItem("u_total_cnt_amt_vat").getValue(); //合同总额
    let u_win_bid_svc_amt = mstform.getItem("u_win_bid_svc_amt").getValue(); //中标服务费

    dgrid.getRows().forEach((items) => {
      sum_cnt_amt_vat += parseFloat(items.u_cnt_amt_vat) || 0; //合同现额
      sum_sub_cost_vat += parseFloat(items.u_sub_cost_vat) || 0; // 拟分包成本含税
      sum_sub_cost += parseFloat(items.u_sub_cost) || 0; // 拟分包成本未税
      sum_pur_cost_vat += parseFloat(items.u_pur_cost_vat) || 0; // 拟采购成本含税
      sum_pur_cost += parseFloat(items.u_pur_cost) || 0; // 拟采购成本未税
      sum_self_cost_vat += parseFloat(items.u_self_cost_vat) || 0; //拟自制成本含税
      sum_self_cost += parseFloat(items.u_self_cost) || 0; //拟自制成本未税
    });
    dgrid1.getRows().forEach((items) => {
      sum_impl_cost_vat += parseFloat(items.u_total_impl_amt) || 0;
    });
    dgrid2.getRows().forEach((items) => {
      sum_svc_cost_vat += parseFloat(items.u_total_svc_amt) || 0;
    });
    dgrid3.getRows().forEach((items) => {
      sum_sec_dev_amt += parseFloat(items.u_rd_expenses) || 0;
    });

    sum_cost_vat = sum_sub_cost_vat + sum_pur_cost_vat + sum_self_cost_vat + sum_impl_cost_vat + sum_svc_cost_vat + sum_sec_dev_amt;
    sum_cost = sum_sub_cost + sum_pur_cost + sum_self_cost + sum_impl_cost_vat + sum_svc_cost_vat + sum_sec_dev_amt;

    $NG.updateState((updater) => {
      updater.data.p_form_equipment_list.setProps({
        u_cnt_amt_vat: sum_cnt_amt_vat, //合同现额
        u_sub_cost: sum_sub_cost_vat, //拟分包含税
        u_sub_cost_amt: sum_sub_cost, //拟分包不含税
        u_pur_cost_vat: sum_pur_cost_vat, //拟采购成本含税
        u_pur_cost_amt: sum_pur_cost, //拟采购成本未税
        u_self_cost_vat: sum_self_cost_vat, //拟自制成本含税
        u_self_cost: sum_self_cost, //拟自制成本未税
        u_implement_amt: sum_impl_cost_vat,
        u_svc_cost_amt: sum_svc_cost_vat,
        u_sec_dev_amt: sum_sec_dev_amt,

        u_total_cost_amt_vat: sum_cost_vat, //总成本含税
        u_total_cost_amt: sum_cost, //总成本不含税
        u_revenue_cost_gm: u_total_cnt_amt_vat - sum_cost_vat, //收入成本毛利
        u_signed_gm_rate: (u_total_cnt_amt_vat - sum_cost_vat) / u_total_cnt_amt_vat, //签单毛利率
        u_svc_amt_rate: u_win_bid_svc_amt / u_total_cnt_amt_vat, //服务费率
        u_bid_gm_rate: (u_total_cnt_amt_vat - sum_cost_vat - u_win_bid_svc_amt) / u_total_cnt_amt_vat, //投标毛利率

        u_sub_cost_ratio: sum_sub_cost_vat / sum_cost_vat, //拟分包成本占比
        u_pur_cost_ratio: sum_pur_cost_vat / sum_cost_vat, //拟采购成本占比
        u_self_cost_ratio: sum_self_cost_vat / sum_cost_vat, //拟自制成本占比
        u_implement_cost_ratio: sum_impl_cost_vat / sum_cost_vat,
        u_svc_cost_ratio: sum_svc_cost_vat / sum_cost_vat,
        u_sec_dev_ratio: sum_sec_dev_amt / sum_cost_vat,
      });
    });
    console.log("u_total_cost_amt_vat:" + mstform.getItem("u_total_cost_amt_vat").getValue());
    console.log("caculatedgrid end");
  }

  function insertClick() {
    var dgrid = $NG.getCmpApi("p_form_equipment_list_d");
    var orirow = dgrid.getCheckedIndexes()[0] !== undefined ? dgrid.getCheckedIndexes()[0] : dgrid.getAllData().table.newRow.length;
    var maxrow = dgrid.getAllData().table.newRow.length;
    console.log(orirow);
    dgrid.addRows();
    setTimeout(function () {
      console.log(maxrow);
      dgrid.moveRow(maxrow, orirow + 1);
    }, 100); // 延迟 100 毫秒，视具体情况可以调整这个值
  }

  function getCntDInfoByPhid(record) {
    $NG.execServer("getCntDInfoByPhid", { cnd_id: mstform.getItem("u_cnt").getValue(), phid: record.u_cnt_item }, function (res) {
      if (res.count > 0) {
        var data = JSON.parse(res.data)[0].extendObjects; //单返回值
        record.u_cnt_item_no = data.item_no; //合同清单编码
        record.u_spec = data.user_ggxh; //规格型号
        record.u_msunit = data.unit_phid;
        record.u_msunit_EXName = data.unit_name; //计量单位
        record.u_tech_params = data.user_jscs; //技术参数
        record.u_brand = data.brand_phid;
        record.u_brand_EXName = data.brand_name; //品牌
        record.u_pc_subitem_category = data.user_gcfxfl; //工程分项分类
        record.u_qty = data.qty; //数量
        record.u_sub_qty = data.qty; //数量
        record.u_pur_qty = data.qty; //数量
        record.u_self_qty = data.qty; //数量
        record.u_cnt_item_tax_rate = data.taxrate; //税率

        record.u_cnt_prc_vat = data.prc_vat_fc; //含税单价
        record.u_cnt_prc = data.prc_fc; //未税单价
        record.u_cnt_amt_vat = data.amt_vat_fc; //含税金额
        record.u_cnt_amt = data.amt_fc; //未税金额
      } else {
        console.log(record.u_cnt_item + "没有找到合同清单");
      }
      dgrid.refreshView();
    });
  }
  function getCntDInfoByNo(record) {
    if (mstform.getItem("u_cnt_no").getValue() && record.u_cnt_item_no) {
      $NG.execServer("getCntDInfoByNo", { cnd_id: mstform.getItem("u_cnt_no").getValue(), item_no: "'" + record.u_cnt_item_no + "'" }, function (res) {
        if (res.count > 0) {
          var data = JSON.parse(res.data)[0].extendObjects; //单返回值

          record.u_cnt_item = data.phid; //合同清单ID
          record.u_cnt_item_EXName = data.item_name; //合同清单名称
          record.u_model = data.user_ggxh; //规格型号
          u_msunit = data.unit_phid; //计量单位
          u_msunit_EXName = data.unit_name; //计量单位
        } else {
          console.log("没有找到合同清单");
          record.u_cnt_item = null;
          record.u_cnt_item_EXName = null;
        }
        dgrid.refreshView();
      });
    }
  }

  function cntDFilter() {
    $NG.updateUI((updater) =>
      updater.editGrid.p_form_equipment_list_d.u_cnt_item.setProps((p) => {
        return {
          ...p,
          editor: {
            ...p.editor,
            clientSqlFilter: {
              pphid: $NG.getCmpApi("p_form_equipment_list").getItem("u_cnt").getValue() || 0,
            },
          },
        };
      })
    );
  }

  ////////////////////////////////////////////////////////////--commonfunction--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--commonfunction--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--commonfunction--////////////////////////////////////////////////////////////
  //自动获取设备清单的实施费用和服务费用
  if (page.oType == page.OType.Add || page.oType == page.OType.Edit) {
    console.log(page.oType); //新增 修改 查看 工作流
    var dgrid1 = $NG.getCmpApi("p_form_equipment_list_impl");
    var dgrid2 = $NG.getCmpApi("p_form_equipment_list_svc");
    var dgrid3 = $NG.getCmpApi("p_form_equipment_list_rd");

    useValuesChange(({ args }) => {
      console.log(args[0]);
      danjvchaxun();
    }, "p_form_equipment_list.u_cnt");
  }
  async function danjvchaxun() {
    await dgrid1.clearRows();
    await dgrid2.clearRows();
    await dgrid3.clearRows();
    if (dgrid1) {
      await $NG.execServer("get_impl_cost_budget_info", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
        console.log(`实施费请求`, res);
        if (res.count == 0) return;
        const data = JSON.parse(res.data);
        console.log(res.data);
        //默认增行,批量新增表体数据
        var gridArr = []; //定义表体数组
        var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
        for (var i = 0; i < gridCount; i++) {
          var gridObj = {};
          //对表体字段进行赋值,可以取数据库中的值进行赋值
          gridObj.u_bill_no = data[i].extendObjects.bill_no;
          gridObj.u_total_impl_amt = data[i].extendObjects.u_total_impl_amt;
          gridObj.u_total_impl_labor_amt = data[i].extendObjects.u_total_impl_labor_amt;
          gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
          gridObj.u_total_sec_dev_amt = data[i].extendObjects.u_total_sec_dev_amt;
          gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
          gridObj.u_source_phid = data[i].extendObjects.phid;
          gridArr.push(gridObj);
          if (data[i].extendObjects.app_status != 1) {
            window._lsz_catch_status["impl"].push(data[i].extendObjects.bill_no);
          }
        }
        //调用新增表体行数据的函数
        dgrid1.addRows(gridArr);
      });
    }
    if (dgrid2) {
      await $NG.execServer("get_svc_cost_budget_info", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
        console.log(`服务请求`, res);
        if (res.count == 0) return;
        const data = JSON.parse(res.data);
        console.log(res.data);
        //默认增行,批量新增表体数据
        var gridArr = []; //定义表体数组
        var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
        for (var i = 0; i < gridCount; i++) {
          //对表体字段进行赋值,可以取数据库中的值进行赋值
          var gridObj = {};
          gridObj.u_bill_no = data[i].extendObjects.bill_no;
          gridObj.u_total_svc_amt = data[i].extendObjects.u_total_svc_amt;
          gridObj.u_total_svc_labor_amt = data[i].extendObjects.u_total_svc_labor_amt;
          gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
          gridObj.u_source_phid = data[i].extendObjects.phid;
          // gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
          gridArr.push(gridObj);
          if (data[i].extendObjects.app_status != 1) {
            window._lsz_catch_status["svc"].push(data[i].extendObjects.bill_no);
          }
        }
        //调用新增表体行数据的函数
        dgrid2.addRows(gridArr);
      });
    }
    if (dgrid3) {
      await $NG.execServer("getDevCostBudgetInfo", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
        console.log(`研发费请求`, res);
        if (res.count == 0) return;
        const data = JSON.parse(res.data);
        console.log(res.data);
        //默认增行,批量新增表体数据
        var gridArr = []; //定义表体数组
        var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
        for (var i = 0; i < gridCount; i++) {
          //对表体字段进行赋值,可以取数据库中的值进行赋值
          var gridObj = {};
          gridObj.u_bill_no = data[i].extendObjects.bill_no;
          gridObj.u_rdrg_expenses_total = data[i].extendObjects.u_total_labor_amt;
          gridObj.u_rcfy_total = data[i].extendObjects.u_total_daily_amt;
          gridObj.u_rd_expenses = data[i].extendObjects.u_total_dev_amt;
          gridObj.u_source_phid = data[i].extendObjects.phid;
          // gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
          gridArr.push(gridObj);
          if (data[i].extendObjects.app_status != 1) {
            window._lsz_catch_status["rd"].push(data[i].extendObjects.bill_no);
          }
        }
        //调用新增表体行数据的函数
        dgrid3.addRows(gridArr);
      });
    }
    //页面条件
    if (page.oType == "add" || page.oType == "edit" || page.oType == "copy") {
      checkImpdataStatus();
    }
  }

  function checkImpdataStatus() {
    console.log("是否审核----", window._lsz_catch_status);
    // 检查 window._lsz_catch_status 是否为空
    if (window._lsz_catch_status) {
      // 检查所有的数组是否都为空
      for (let key in window._lsz_catch_status) {
        if (Array.isArray(window._lsz_catch_status[key]) && window._lsz_catch_status[key].length > 0) {
          checkImpFlg = false;
          break; // 找到一个非空数组就可以结束检查
        } else {
          checkImpFlg = true;
        }
      }
      if (!checkImpFlg) {
        // 如果有非空数组，继续你的逻辑
        let title = "预算费用包含未审核明细：";
        const expenseTypes = {
          impl: "实施费用预算编码",
          svc: "服务费用预算编码",
          rd: "二开费用预算编码",
        };
        for (let key in window._lsz_catch_status) {
          if (expenseTypes[key]) {
            window._lsz_catch_status[key].forEach((item, index) => {
              title += `${expenseTypes[key]}：${item}${index === window._lsz_catch_status[key].length - 1 ? "" : "、"}`;
            });
          }
        }
        $NG.alert(title);
      }
    } else {
      checkImpFlg = true;
    }
  }
});

// 自动生产编码 ** 如果想复用，请在全局文件中定义一个 变量：let maxNo=null
ts();
function ts() {
  $NG.execServer("autoSbqdno", { num: formatDate(new Date(), "YYYYmmDD") }, function (res) {
    if (res.count !== 0) {
      const _data = JSON.parse(res.data)[0].extendObjects;
      console.log(`最大编号`, _data);
      maxNo = Number(_data.u_equipment_list_no);
    } else {
      maxNo = Number(formatDate(new Date(), "YYYYmmDD") + "000000");
    }
  });
}
function autoCreateNo(int) {
  let str = String(maxNo).slice(-6);
  let num = Number(str) + int;
  const s = formatDate(new Date(), "YYYYmmDD") + String(num).padStart(6, "0");
  console.log(`测试编号`, s, str, num);
  return s;
}
// 日期格式化
function formatDate(dateStr, outputFormat) {
  const date = new Date(dateStr);

  if (isNaN(date)) {
    return "无效的日期字符串";
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");

  let formattedDate;

  switch (outputFormat) {
    case "yyyy-mm-dd":
      formattedDate = `${year}-${month}-${day}`;
      break;
    case "yyyy-mm-dd HH:mm":
      formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
      break;
    // 可以根据需要继续添加其他格式的处理逻辑
    case "YYYYmmDD":
      formattedDate = `${year}${month.padStart(2, "0")}${day.padStart(2, "0")}`;
      break;
    default:
      formattedDate = "不支持的输出格式";
  }

  return formattedDate;
}
